#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: xmind_to_json.py
# Author: 
# Date: 2025-08-24

"""
功能描述: 读取XMind文件内容并输出为JSON格式
"""
import os
import json
import xmindparser

def xmind_to_json(xmind_path, output_path=None):
    """将XMind文件转换为JSON格式
    :param xmind_path: XMind文件路径
    :param output_path: 输出JSON文件路径，默认为同目录下同名.json文件
    :return: JSON数据
    """
    # 检查文件是否存在
    if not os.path.exists(xmind_path):
        raise FileNotFoundError(f"文件 {xmind_path} 不存在")
    
    # 使用xmindparser解析XMind文件
    xmind_content = xmindparser.xmind_to_dict(xmind_path)
    print("解析的XMind文件：")
    print(xmind_content)
    
    # 提取中心主题
    central_topic = xmind_content[0]['topic']
    
    def process_node(node):
        # 创建当前节点的基础结构
        new_node = {"title": node['title']}
        
        # 检查是否存在子主题
        if 'topics' in node and node['topics']:
            # 处理子节点
            children = [process_node(child) for child in node['topics']]
            # 只有当子节点不为空时才添加children属性
            if children:
                new_node["children"] = children
            
        return new_node
    
    # 处理中心主题并获取转换后的数据
    processed_data = process_node(central_topic)
    
    print("处理后的XMind文件数据：")
    print(processed_data)
    
    # 如果未指定输出路径，则使用默认路径
    if output_path is None:
        base_name = os.path.splitext(os.path.basename(xmind_path))[0]
        output_path = os.path.join(os.path.dirname(xmind_path), f'{base_name}.json')
    
    # 保存JSON格式文件
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(processed_data, f, ensure_ascii=False, indent=4)
    print(f"成功输出XMind内容到: {output_path}")
    return processed_data

if __name__ == "__main__":
    # 获取示例文件路径
    from ui_code.common_ui import get_project_root
    xmind_path = get_project_root() / "files" / "【示例】商品详情qwer12345.xmind"
    
    try:
        xmind_to_json(str(xmind_path))
    except Exception as e:
        print(f"转换失败: {e}")